package com.juyu.miliao.api.config;

import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author jh
 * 2018/9/26
 */
@Configuration
@EnableConfigurationProperties(DozerProperties.class)
public class DozerMapperConfig {

    @Resource
    private DozerProperties dozerProperties;

    @Value("${dozer.mapping-files}")
    private String dozerMappingFiles;

    @Bean
    public DozerBeanMapper mapper() {
        DozerBeanMapper mapper = new DozerBeanMapper();
        if (dozerMappingFiles.isEmpty()) {
            throw new RuntimeException("dozer mapping配置文件不能为空");
        }
        ///List<String> mappings = loadMappingFiles(dozerProperties.getMappingFiles());
        String[] files = StringUtils.split(dozerMappingFiles, ",");
        mapper.setMappingFiles(Arrays.asList(files));
        return mapper;
    }

    // TODO: 2018/9/27 匹配符号无法加载 
    private List<String> loadMappingFiles(org.springframework.core.io.Resource[] mappingFiles) {
        List<String> mappings = new ArrayList<>();
        if (mappingFiles != null && mappingFiles.length > 0) {
            try {
                for (org.springframework.core.io.Resource mappingFile : mappingFiles) {
                    URL url = mappingFile.getURL();
                    mappings.add(url.toString());
                }
            } catch (IOException e) {
                throw new RuntimeException("dozer mapping读取异常");
            }
        }

        return mappings;
    }


}
